<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="common-nav-bar"
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    />

    <div class="main">
      <h1 class="title">{{ articleInfo.title }}</h1>

      <van-cell class="author-info" value="内容" center>
        <van-image
          class="avatar"
          round
          slot="icon"
          :src="articleInfo.aut_photo"
        />
        <span class="name" slot="title">{{ articleInfo.aut_name }}</span>

        <van-button
          class="follow-btn"
          round
          :icon="articleInfo.is_followed ? 'success' : 'plus'"
          size="small"
          :type="articleInfo.is_followed ? 'default' : 'info'"
          @click="handleFollow"
          :loading="isFollowing"
          >{{ articleInfo.is_followed ? '已关注' : '关注' }}</van-button
        >
        <span slot="label" class="pubdate">{{
          articleInfo.pubdate | formatTimeFromNow
        }}</span>
      </van-cell>
      <div
        class="markdown-body"
        ref="refContent"
        v-html="articleInfo.content"
      ></div>
      <!-- 文章评论 -->
      <comment-list
        :source="articleId"
        :list="commentList"
        @update-reply-count="replyCount = $event"
        @reply-click="onReplyClick"
      ></comment-list>
    </div>

    <!-- 底栏 -->
    <div class="article-bottom">
      <div class="btn-wrap">
        <van-button
          class="comment-btn"
          plain
          round
          size="small"
          type="primry"
          @click="isPostShow = true"
          >写评论</van-button
        >
      </div>
      <div class="icon-wrap">
        <van-icon name="comment-o" :badge="replyCount" />
        <van-icon
          :color="this.articleInfo.is_collected ? 'orange' : ''"
          :name="this.articleInfo.is_collected ? 'star' : 'star-o'"
          @click="handleCollect"
        />
        <van-icon
          :color="this.articleInfo.attitude === 1 ? 'red' : ''"
          :name="this.articleInfo.attitude === 1 ? 'good-job' : 'good-job-o'"
          @click="handleLiked"
        />
        <van-icon name="share" />
      </div>
    </div>

    <!-- 评论弹出窗 -->
    <van-popup v-model="isPostShow" position="bottom">
      <comment-post :target="articleId" @post-success="onPostSuccess" />
    </van-popup>

    <!-- 评论评论的弹出窗 -->
    <van-popup v-model="isReplyShow" position="bottom">
      <comment-reply
        v-if="isReplyShow"
        :comment="currentComment"
        :articleId="articleId"
        @close="isReplyShow = false"
      />
    </van-popup>
  </div>
</template>

<script>
import {
  apiGetSingleArticle,
  addCollected,
  removeCollected,
  addLiked,
  removeLiked
} from '@/api/article'
import { addFollow, removeFollow } from '@/api/user'
import 'github-markdown-css'
import { ImagePreview } from 'vant'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'

export default {
  name: 'Article',
  components: {
    CommentList,
    CommentPost,
    CommentReply
  },
  props: {
    // 这个是动态路由的参数
    articleId: {
      type: [String, Number, Object],
      required: true
    }
  },
  data() {
    return {
      articleInfo: {},
      isFollowing: false,
      isPostShow: false,
      isReplyShow: false,
      commentList: [],
      replyCount: 0,
      currentComment: {}
    }
  },
  created() {
    this.getArticleInfo()
  },
  mounted() {
    // this.setImagesPreview()
  },
  methods: {
    async getArticleInfo() {
      const { data } = await apiGetSingleArticle(this.articleId)
      // console.log(data)
      this.articleInfo = data.data

      // nextTick 表示等到 dom 渲染完成后，执行操作
      /**
       * 数据改变影响视图更新（DOM数据）不是立即的
       * 所以如果需要在修改数据之后马上操作被该数据影响的视图 DOM，
       * 需要把这个代码放到 $nextTick 中
       */
      this.$nextTick(() => {
        this.setImagesPreview()
      })
    },
    // 给文章中的图片加上 预览功能
    setImagesPreview() {
      const dom = this.$refs.refContent
      const list = dom.querySelectorAll('img')

      const imgList = []

      list.forEach((element, index) => {
        imgList.push(element.src)
        element.onclick = () => {
          ImagePreview({
            images: imgList,
            startPosition: index
          })
        }
      })
    },
    async handleFollow() {
      this.isFollowing = true
      // 已关注状态，执行取消关注任务，未关注状态，执行关注任务
      if (this.articleInfo.is_followed) {
        await removeFollow(this.articleInfo.aut_id)
      } else {
        await addFollow(this.articleInfo.aut_id)
      }

      this.articleInfo.is_followed = !this.articleInfo.is_followed
      this.isFollowing = false
    },
    async handleCollect() {
      this.$toast.loading({
        type: 'loading',
        forbidClick: true
      })
      if (this.articleInfo.is_collected) {
        await removeCollected(this.articleInfo.art_id)
      } else {
        await addCollected(this.articleInfo.art_id)
      }

      this.$toast(
        `${this.articleInfo.is_collected ? '取消收藏成功' : '收藏成功'}`
      )

      this.articleInfo.is_collected = !this.articleInfo.is_collected
    },
    async handleLiked() {
      this.$toast.loading({
        type: 'loading',
        forbidClick: true
      })
      if (this.articleInfo.attitude === 1) {
        await removeLiked(this.articleInfo.art_id)
        this.articleInfo.attitude = 0
      } else {
        await addLiked(this.articleInfo.art_id)
        this.articleInfo.attitude = 1
      }

      this.$toast(
        `${this.articleInfo.attitude === 1 ? '点赞成功' : '取消点赞成功'}`
      )
    },
    onPostSuccess(comment) {
      // 发布评论成功后
      // 将新的评论放到评论列表头部
      this.commentList.unshift(comment)
      // 关闭评论窗口
      this.isPostShow = false
      // 评论数量加 1
      this.replyCount++
    },
    onReplyClick(comment) {
      this.isReplyShow = true
      console.log(comment)
      this.currentComment = comment
    }
  }
}
</script>

<style lang="less" scoped>
.article-container {
  background-color: #ffffff;
  .main {
    height: calc(100vh - 85px);
    overflow: auto;
    .title {
      font-size: 20px;
      padding: 0 14px;
    }
    .author-info {
      .avatar {
        width: 35px;
        height: 35px;
        margin-right: 8px;
      }
      .name {
        font-size: 12px;
        color: #333333;
      }
      .pubdate {
        font-size: 11px;
        color: #b4b4b4;
      }
      .follow-btn {
        width: 85px;
        height: 29px;
      }
    }
    .markdown-body {
      padding: 14px;
    }
  }

  .article-bottom {
    box-sizing: border-box;
    border-top: 1px solid #cccccc;
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 40px;
    background-color: #ffffff;
    display: flex;
    .btn-wrap {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      .comment-btn {
        width: 180px;
        height: 28px;
        border: 1px solid #eeeeee;
        font-size: 15px;
        line-height: 23px;
        color: #a7a7a7;
      }
    }
    .icon-wrap {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
      .van-icon {
        flex: 1;
        text-align: center;
        font-size: 18px;
        color: #666666;
        margin: 0 10px;
      }
    }
  }
}
</style>
